<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="人员姓名" prop="personId">
          <el-select v-model="queryParams.personId" placeholder="请选择人员姓名" clearable @change="handleQueryPersonChange">
            <el-option v-for="person in personList" :key="person.id" :label="person.name" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="健康档案" prop="healthRecordId">
          <el-select v-model="queryParams.healthRecordId" placeholder="请选择健康档案" clearable>
            <el-option v-for="health in healthRecordList" :key="health.id" :label="health.name" :value="health.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="医院名称" prop="hospitalName">
          <el-input v-model="queryParams.hospitalName" placeholder="请输入医院名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="就医类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择就医类型" clearable>
            <el-option v-for="dict in doctor_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="departments">
          <el-input v-model="queryParams.departments" placeholder="请输入科室" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="大夫" prop="doctor">
          <el-input v-model="queryParams.doctor" placeholder="请输入大夫" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="就诊时间" prop="time">
          <el-date-picker v-model="queryParams.time" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['health:doctorRecord:add']">新增</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['health:doctorRecord:remove']">删除</el-button>
          <!-- <el-button @click="handleExport" icon="Download" v-hasPermi="['health:doctorRecord:export']">导出</el-button> -->
        </div>
      </div>
      <div class="content-con" v-loading="loading" height="calc(100% - 0.65rem)">
        <el-table v-loading="loading" :data="doctorRecordList" @selection-change="handleSelectionChange" height="calc(100% - 0.65rem)">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" :index="indexMethod" width="50"></el-table-column>
          <el-table-column label="人员姓名" align="center" width="100" prop="personName" />
          <el-table-column label="健康档案" align="center" width="160" prop="healthRecordName" />
          <el-table-column label="医院名称" align="center" width="160" prop="hospitalName" />
          <el-table-column label="就医类型" align="center" width="120" prop="type">
            <template #default="scope">
              <dict-tag :options="doctor_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="科室" align="center" width="150" prop="departments" />
          <el-table-column label="大夫" align="center" width="80" prop="doctor" />
          <el-table-column label="陪同人" align="center" width="120" prop="partner" />
          <el-table-column label="就诊时间" align="center" prop="visitingTime" width="160"> </el-table-column>
          <el-table-column label="总费用（元）" align="center" width="120" prop="totalCost" />
          <el-table-column label="诊断结果" align="center" prop="diagnosis" />
          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button :icon="item.icon" v-hasPermi="item.hasPermi" circle @click="handleOperate(item.id, scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加或修改就医记录对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="doctorRecordRef" :model="form" :inline="true" :rules="rules" label-width="120px">
        <el-form-item label="人员姓名" prop="personId">
          <el-select v-model="form.personId" placeholder="请选择人员姓名" @change="handlePersonChange" clearable>
            <el-option v-for="person in personList" :key="person.id" :label="person.name" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="健康档案" prop="healthRecordId">
          <el-select v-model="form.healthRecordId" placeholder="请选择健康档案" clearable>
            <el-option v-for="health in healthRecordList" :key="health.id" :label="health.name" :value="health.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="医院名称" prop="hospitalName">
          <el-input v-model="form.hospitalName" placeholder="请输入医院名称" />
        </el-form-item>
        <el-form-item label="就医类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择就医类型">
            <el-option v-for="dict in doctor_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="departments">
          <el-input v-model="form.departments" placeholder="请输入科室" />
        </el-form-item>
        <el-form-item label="大夫" prop="doctor">
          <el-input v-model="form.doctor" placeholder="请输入大夫" />
        </el-form-item>
        <el-form-item label="就诊时间" prop="visitingTime">
          <el-date-picker clearable v-model="form.visitingTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择就诊时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="陪同人" prop="partner">
          <el-input v-model="form.partner" placeholder="请输入陪同人" />
        </el-form-item>

        <el-form-item label="总费用" style="width: 792px" prop="totalCost">
          <el-input v-model="form.totalCost" type="number" placeholder="请输入总费用">
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="诊断结果" style="width: 792px" prop="diagnosis">
          <el-input v-model="form.diagnosis" placeholder="请输入诊断结果" />
        </el-form-item>
        <el-form-item label="处理及医嘱" style="width: 792px" prop="prescribe">
          <el-input v-model="form.prescribe" type="textarea" placeholder="请输入处理及医嘱" />
        </el-form-item>
        <el-form-item label="费用明细" style="width: 792px" prop="costDetail">
          <el-input v-model="form.costDetail" type="textarea" placeholder="请输入费用明细" />
        </el-form-item>
        <el-form-item label="备注" style="width: 792px" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看就医记录'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改分期历史明细对话框 -->
    <el-dialog title="添加费用明细" v-model="openDetail" width="500px" append-to-body>
      <el-form ref="doctorRecordCostRef" :model="formDetail" :rules="rulesDetail" label-width="120px">
        <el-form-item label="费用类型" prop="type">
          <el-select v-model="formDetail.type" @change="handleTypeChange" placeholder="请选择费用类型">
            <el-option v-for="dict in cost_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产生时间" prop="costTime">
          <el-date-picker clearable v-model="formDetail.costTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择产生时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="治疗类型" v-show="showMedicine" prop="treatType">
          <el-select v-model="form.treatType" placeholder="请选择用药类型" @change="handleTreatTypeChange">
            <el-option v-for="dict in mar_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="showMedicine" label="药品名称" prop="medicineId">
          <el-select v-model="formDetail.medicineId" placeholder="请选择药品名称" @change="handleMedicineChange" clearable>
            <el-option v-for="medicine in medicineList" :key="medicine.id" :label="medicine.shortNameBrandPackaging" :value="medicine.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="showCheckType" label="检查类型" prop="checkType">
          <el-select v-model="formDetail.checkType" @change="handleCheckTypechange" clearable placeholder="请选择检查类型">
            <el-option v-for="dict in check_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="showNursingType" clearable label="护理治疗" prop="checkType">
          <el-select v-model="formDetail.checkType" @change="handleNursingTypechange" placeholder="请选择护理治疗">
            <el-option v-for="dict in nursing_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费用名称" v-show="false" prop="costName">
          <el-input v-model="formDetail.costName" placeholder="请输入费用名称" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="formDetail.price" type="number" @change="handlePriceChange" placeholder="请输入单价">
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-input v-model="formDetail.count" type="number" @change="handleCountChange" placeholder="请输入数量"> </el-input>
        </el-form-item>
        <el-form-item label="单位" disabled prop="unit">
          <el-select v-model="formDetail.unit" clearable placeholder="请选择单位">
            <el-option v-for="dict in package_unit" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总价" prop="totalCost">
          <el-input v-model="formDetail.totalCost" type="number" placeholder="请输入总价">
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formDetail.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDetail">确 定</el-button>
          <el-button @click="cancelDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改费用明细对话框 -->
    <el-dialog title="查看添加费用明细" v-model="detailOpen" width="1150px" append-to-body>
      <div class="basic-information">
        <div class="main-con">
          <div class="title-con">
            <div class="title">基本信息</div>
            <div class="operate-btn-con">
              <el-button @click="handleAddDetail" icon="Plus" v-hasPermi="['health:doctorRecord:add']">新增</el-button>
              <el-button icon="Delete" @click="handleDeleteDetail" v-hasPermi="['health:doctorRecord:remove']">删除明细</el-button>
              <el-button @click="handleUpdateCost" icon="Expand" v-hasPermi="['health:doctorRecord:add']">总费用汇总</el-button>
            </div>
          </div>
          <div class="content-con">
            <el-table v-loading="loading" @selection-change="handleSelectionChange" :data="doctorRecordCostList">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column type="index" label="序号" :index="indexMethod" width="50"></el-table-column>
              <el-table-column label="产生时间" align="center" prop="costTime" width="170"> </el-table-column>
              <el-table-column label="费用类型" width="100" align="center" prop="type">
                <template #default="scope">
                  <dict-tag :options="cost_type" :value="scope.row.type" />
                </template>
              </el-table-column>
              <el-table-column label="费用名称" align="center" prop="costName" />
              <el-table-column label="单价（元）" align="center" width="100" prop="price" />
              <el-table-column label="数量" align="center" width="80" prop="count" />
              <el-table-column label="单位" align="center" width="80" prop="unit">
                <template #default="scope">
                  <dict-tag :options="package_unit" :value="scope.row.unit" />
                </template>
              </el-table-column>
              <el-table-column label="总价（元）" align="center" width="100" prop="totalCost" />

              <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
                <template v-slot="scope">
                  <div class="ctrl-btn d-flex">
                    <el-tooltip v-for="item in operateDetailList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                      <el-button :icon="item.icon" v-hasPermi="item.hasPermi" circle @click="handleDetailOperate(item.id, scope.row)"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer> </template>
    </el-dialog>
  </div>
</template>

<script setup name="DoctorRecord">
import { listDoctorRecord, getDoctorRecord, delDoctorRecord, addDoctorRecord, updateDoctorRecord } from '@/api/health/doctorRecord'
import { listDoctorRecordCost, getDoctorRecordCost, delDoctorRecordCost, addDoctorRecordCost, updateDoctorRecordCost } from '@/api/health/doctorRecordCost'
import { listPerson, getPerson } from '@/api/health/person'
import { listMedicineBasic, getMedicineBasic } from '@/api/health/medicineBasic'
import { listHealthRecord } from '@/api/health/healthRecord'
import dayjs from 'dayjs'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()
const { doctor_type, cost_type, check_type, package_unit, nursing_type, mar_type } = proxy.useDict(
  'doctor_type',
  'cost_type',
  'check_type',
  'package_unit',
  'nursing_type',
  'mar_type'
)
const medicineList = ref([])
const doctorRecordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const personList = ref([])
const healthRecordList = ref([])

const detailOpen = ref(false)
const openDetail = ref(false)
const titleDetail = ref('')
const doctorRecordCostList = ref([])
const currentDoctorRecordId = ref('')
const currentHealthRecordId = ref('')
const currentPersonId = ref('')
const showCheckType = ref(false)
const showNursingType = ref(false)
const showMedicine = ref(false)
const operateList = ref([
  { id: 'detail', icon: 'Grid', title: '费用明细', hasPermi: ['health:doctorRecord:query'] },
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['health:doctorRecord:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['health:doctorRecord:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['health:doctorRecord:remove'] }
])
const operateDetailList = ref([
  { id: 'copy', icon: 'Link', title: '复制', hasPermi: ['health:doctorRecord:edit'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['health:doctorRecord:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['health:doctorRecord:remove'] }
])
const data = reactive({
  form: {},
  formDetail: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    hospitalName: null,
    departments: null,
    doctor: null,
    healthRecordId: null,
    time: '',
    personId: null
  },
  queryPersonParams: {
    pageNum: 1,
    pageSize: 1000
  },
  queryMedicineParams: {
    pageNum: 1,
    treatmentType: null,
    pageSize: 1000
  },
  queryHealthRecordParams: {
    pageNum: 1,
    personId: null,
    state: '1',
    pageSize: 1000
  },
  rules: {
    personId: [{ required: true, message: '人员姓名不能为空', trigger: 'blur' }],
    hospitalName: [{ required: true, message: '医院名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '就医类型不能为空', trigger: 'change' }],
    departments: [{ required: true, message: '科室不能为空', trigger: 'blur' }],
    doctor: [{ required: true, message: '大夫不能为空', trigger: 'blur' }],
    partner: [{ required: true, message: '陪同人不能为空', trigger: 'blur' }],
    totalCost: [{ required: true, message: '总费用不能为空', trigger: 'blur' }],
    healthRecordId: [{ required: true, message: '健康档案不能为空', trigger: 'blur' }],
    visitingTime: [{ required: true, message: '就诊时间不能为空', trigger: 'blur' }],
    prescribe: [{ required: true, message: '处理及医嘱不能为空', trigger: 'blur' }],
    diagnosis: [{ required: true, message: '诊断结果不能为空', trigger: 'blur' }]
  },
  rulesDetail: {
    doctorRecordId: [{ required: true, message: '费用id不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '费用类型不能为空', trigger: 'blur' }],
    costTime: [{ required: true, message: '产生时间不能为空', trigger: 'blur' }],
    costName: [{ required: true, message: '费用名称不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
    totalCost: [{ required: true, message: '总价不能为空', trigger: 'blur' }],
    unit: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
    count: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
  }
})
/** 查询药品管理列表 */
function getMedicineList() {
  listMedicineBasic(queryMedicineParams.value).then((response) => {
    medicineList.value = response.rows
  })
}
const handleTreatTypeChange = (type) => {
  queryMedicineParams.value.treatmentType = type

  listMedicineBasic(queryMedicineParams.value).then((response) => {
    medicineList.value = response.rows
  })
}
const handleOperate = (operate, row) => {
  switch (operate) {
    case 'detail':
      handleDetail(row)
      break
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      break
  }
}

const { queryParams, form, formDetail, rules, queryPersonParams, queryMedicineParams, queryHealthRecordParams, rulesDetail } = toRefs(data)

const handlePersonChange = (personId) => {
  queryHealthRecordParams.personId = personId
  listHealthRecord(queryHealthRecordParams).then((response) => {
    healthRecordList.value = response.rows
    if (response.rows.length > 0) {
      form.value.healthRecordId = healthRecordList.value[0].id
    }
  })
}
const handleQueryPersonChange = (personId) => {
  queryHealthRecordParams.personId = personId
  queryParams.value.healthRecordId = null
  listHealthRecord(queryHealthRecordParams).then((response) => {
    healthRecordList.value = response.rows
  })
}

const handleCountChange = (count) => {
  if (formDetail.value.price != null) {
    formDetail.value.totalCost = parseFloat(count * formDetail.value.price).toFixed(2)
  }
}
const handlePriceChange = (price) => {
  if (formDetail.value.count != null) {
    formDetail.value.totalCost = parseFloat(price * formDetail.value.count).toFixed(2)
  }
}
const handleNursingTypechange = (type) => {
  const selectedOption = nursing_type.value.find((option) => option.value === type)
  if (selectedOption) {
    formDetail.value.costName = selectedOption.label
  }
}

const handleCheckTypechange = (type) => {
  const selectedOption = check_type.value.find((option) => option.value === type)
  if (selectedOption) {
    formDetail.value.costName = selectedOption.label
  }
}

const handleMedicineChange = (medicineId) => {
  getMedicineBasic(medicineId).then((response) => {
    formDetail.value.unit = response.data.packageUnit
    formDetail.value.costName = response.data.shortNameBrandPackaging
  })
}

const handleTypeChange = (type) => {
  //挂号费
  if (type == '1') {
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = false
    formDetail.value.costName = '挂号费'
    formDetail.value.count = 1
    formDetail.value.unit = '6'
  } else if (type == '2') {
    //检测检查
    showCheckType.value = true
    showNursingType.value = false
    showMedicine.value = false
    formDetail.value.count = 1
    formDetail.value.unit = '5'
  } else if (type == '3') {
    //药品
    getMedicineList()
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = true
    formDetail.value.count = 1
  } else if (type == '4') {
    //护理治疗
    showCheckType.value = false
    showNursingType.value = true
    showMedicine.value = false
    formDetail.value.unit = '6'
    formDetail.value.count = 1
  } else if (type == '5') {
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = false
    formDetail.value.costName = '交通费'
    formDetail.value.unit = '6'
    formDetail.value.count = 1
  } else if (type == '6') {
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = false
    formDetail.value.costName = '餐饮'
    formDetail.value.unit = '6'
    formDetail.value.count = 1
  } else {
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = false
    formDetail.value.costName = '其他'
    formDetail.value.count = 1
    formDetail.value.unit = null
  }
}

/** 新增按钮操作 */
function handleAddDetail() {
  resetDetail()
  getMedicineList()
  titleDetail.value = '添加费用明细'
  openDetail.value = true
}

const handleDetailOperate = (operate, row) => {
  switch (operate) {
    case 'copy':
      handleCopy(row)
      break
    case 'edit':
      handleUpdateDetail(row)
      break
    case 'delete':
      handleDeleteDetail(row)
      break
    default:
      break
  }
}
/** 复制按钮操作 */
function handleCopy(row) {
  resetDetail()
  getDoctorRecordCost(row.id).then((response) => {
    formDetail.value = response.data
    const type = response.data.type
    //挂号费
    if (type == '1') {
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = false
    } else if (type == '2') {
      //检测检查
      showCheckType.value = true
      showNursingType.value = false
      showMedicine.value = false
    } else if (type == '3') {
      //药品
      getMedicineList()
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = true
    } else if (type == '4') {
      //护理治疗
      showCheckType.value = false
      showNursingType.value = true
      showMedicine.value = false
    } else if (type == '5') {
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = false
    } else if (type == '6') {
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = false
    } else if (type == '7') {
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = false
    }
    formDetail.value.id = null
    openDetail.value = true
    titleDetail.value = '复制费用明细'
  })
}
// 取消按钮
function cancelDetail() {
  openDetail.value = false
  resetDetail()
  //检测检查
  showCheckType.value = false
  showNursingType.value = false
  showMedicine.value = false
}
/** 总利息按钮操作 */
function handleUpdateCost() {
  let totalCost = 0
  for (let i = 0; i < doctorRecordCostList.value.length; i++) {
    if (doctorRecordCostList.value[i].totalCost) {
      totalCost = totalCost + doctorRecordCostList.value[i].totalCost
    }
  }
  getDoctorRecord(currentDoctorRecordId.value).then((response) => {
    form.value = response.data
    form.value.totalCost = totalCost
    if (form.value.id != null) {
      updateDoctorRecord(form.value).then((response) => {
        proxy.$modal.msgSuccess('总费用汇总成功！')
        openDetail.value = false
        getList()
      })
    }
  })
}

/** 删除按钮操作 */
function handleDeleteDetail(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delDoctorRecordCost(_ids)
    })
    .then(() => {
      listDoctorRecordCost({ doctorRecordId: currentDoctorRecordId.value, pageNum: 1, pageSize: 1000 }).then((response) => {
        doctorRecordCostList.value = response.rows
      })
      proxy.$modal.msgSuccess('删除费用明细成功')
    })
    .catch(() => {})
}

/** 提交按钮 */
function submitFormDetail() {
  formDetail.value.personId = currentPersonId.value
  formDetail.value.doctorRecordId = currentDoctorRecordId.value
  formDetail.value.healthRecordId = currentHealthRecordId.value
  proxy.$refs.doctorRecordCostRef.validate((valid) => {
    if (valid) {
      if (formDetail.value.id != null) {
        updateDoctorRecordCost(formDetail.value).then((response) => {
          proxy.$modal.msgSuccess('修改明细成功')
          openDetail.value = false
          listDoctorRecordCost({ doctorRecordId: currentDoctorRecordId.value, pageNum: 1, pageSize: 1000 }).then((response) => {
            doctorRecordCostList.value = response.rows
          })
        })
      } else {
        addDoctorRecordCost(formDetail.value).then((response) => {
          proxy.$modal.msgSuccess('新增明细成功')
          openDetail.value = false
          listDoctorRecordCost({ doctorRecordId: currentDoctorRecordId.value, pageNum: 1, pageSize: 1000 }).then((response) => {
            doctorRecordCostList.value = response.rows
          })
        })
      }
    }
  })
}

/** 修改按钮操作 */
function handleUpdateDetail(row) {
  resetDetail()
  getDoctorRecordCost(row.id).then((response) => {
    formDetail.value = response.data
    const type = response.data.type
    //挂号费
    if (type == '1') {
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = false
    } else if (type == '2') {
      //检测检查
      showCheckType.value = true
      showNursingType.value = false
      showMedicine.value = false
    } else if (type == '3') {
      //药品
      getMedicineList()
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = true
    } else if (type == '4') {
      //护理治疗
      showCheckType.value = false
      showNursingType.value = true
      showMedicine.value = false
    } else if (type == '5') {
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = false
    } else if (type == '6') {
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = false
    } else if (type == '7') {
      showCheckType.value = false
      showNursingType.value = false
      showMedicine.value = false
    }
    openDetail.value = true
    titleDetail.value = '修改费用明细'
  })
}

// 表单重置
function resetDetail() {
  formDetail.value = {
    id: null,
    doctorRecordId: null,
    type: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    healthRecordId: null,
    costTime: null,
    costName: null,
    personId: null,
    totalCost: null,
    price: null,
    count: null,
    unit: null,
    medicineId: null,
    checkType: null
  }
  proxy.resetForm('doctorRecordCostRef')
}
/** 新增按钮操作 */
function handleDetail(row) {
  detailOpen.value = true
  formDetail.value.doctorRecordId = row.id
  currentDoctorRecordId.value = row.id
  currentPersonId.value = row.personId
  currentHealthRecordId.value = row.healthRecordId
  formDetail.value.personId = row.personId
  formDetail.value.doctorRecordId = row.id
  formDetail.value.healthRecordId = row.healthRecordId
  listDoctorRecordCost({ doctorRecordId: row.id, pageNum: 1, pageSize: 1000 }).then((response) => {
    doctorRecordCostList.value = response.rows
  })
}

/** 查询就医记录列表 */
function getList() {
  loading.value = true
  const timeRange = queryParams.value.time
  let st = ''
  let et = ''
  if (timeRange && timeRange.length === 2) {
    st = dayjs(timeRange[0]).format('YYYY-MM-DD')
    et = dayjs(timeRange[1]).format('YYYY-MM-DD')
  }
  queryParams.value.startTime = st
  queryParams.value.endTime = et
  listDoctorRecord(queryParams.value).then((response) => {
    doctorRecordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
/** 查询成员管理列表 */
function getPersonList() {
  listPerson(queryPersonParams.value).then((response) => {
    personList.value = response.rows
    if (response.rows.length > 0) {
      listHealthRecord(queryHealthRecordParams).then((res) => {
        healthRecordList.value = res.rows
      })
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    hospitalName: null,
    departments: null,
    doctor: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    healthRecordId: null,
    visitingTime: null,
    prescribe: null,
    personId: null,
    totalCost: 0,
    partner: null,
    costDetail: null
  }
  proxy.resetForm('doctorRecordRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

//每页显示条数改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}
// 序号翻页递增
const indexMethod = (index) => {
  const nowPage = queryParams.value.pageNum //当前第几页，根据组件取值即可
  const nowLimit = queryParams.value.pageSize //当前每页显示几条，根据组件取值即可
  return index + 1 + (nowPage - 1) * nowLimit // 这里可以理解成一个公式
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看
const handleView = (row) => {
  title.value = '查看就医记录'
  queryHealthRecordParams.personId = row.personId
  listHealthRecord(queryHealthRecordParams).then((response) => {
    healthRecordList.value = response.rows
  })
  form.value = row
  open.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  form.value.visitingTime = dayjs(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss')
  if (personList.value.length > 0) {
    form.value.personId = personList.value[0].id
    queryHealthRecordParams.personId = personList.value[0].id
    listHealthRecord(queryHealthRecordParams).then((response) => {
      healthRecordList.value = response.rows
      if (response.rows.length > 0) {
        form.value.healthRecordId = healthRecordList.value[0].id
      }
    })
  }
  open.value = true
  title.value = '添加就医记录'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  queryHealthRecordParams.personId = row.personId
  listHealthRecord(queryHealthRecordParams).then((response) => {
    healthRecordList.value = response.rows
  })
  const _id = row.id || ids.value
  getDoctorRecord(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改就医记录'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.doctorRecordRef.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateDoctorRecord(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addDoctorRecord(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delDoctorRecord(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'health/doctorRecord/export',
    {
      ...queryParams.value
    },
    `doctorRecord_${new Date().getTime()}.xlsx`
  )
}

getList()
getPersonList()
</script>
